#include "StdAfx.h"
#include "timermgr.h"
#include "../p2psvrapp.h"

INSTANCE_SINGLETON(CTimerMgr)

CTimerMgr::CTimerMgr(void)
{
}

CTimerMgr::~CTimerMgr(void)
{
}

CTimerCloseServer g_timer_close_server;

bool CTimerMgr::Init( void )
{
    m_timer_mgr = CreateTimerManager(this);
    if (!m_timer_mgr)
    {
        return false;
    }

    if (!AddTimer(&g_timer_close_server, false))
    {
        return false;
    }

    return true;
}

void CTimerMgr::UnInit( void )
{
    if (m_timer_mgr)
    {
        m_timer_mgr->Release();
        m_timer_mgr = NULL;
    }
}

void CTimerMgr::OnTimer( HTIMER hTimer, void* pData )
{
    CTimer* timer = (CTimer*)pData;

    if (timer->get_timer() != hTimer)
    {
        return;
    }

    timer->OnTimer();
}

bool CTimerMgr::AddTimer( CTimer* timer, bool exact /*= false*/ )
{
    HTIMER timer_handle = m_timer_mgr->AddTimer(timer->get_elapse(), timer->get_count(), timer, exact);
    if (!timer_handle)
    {
        return false;
    }

    timer->set_timer(timer_handle);

    return true;
}

bool CTimerMgr::ModTimer( CTimer* timer, bool exact /*= false*/ )
{
    return m_timer_mgr->ModTimer(timer->get_timer(), timer->get_elapse(), timer->get_count(), timer, exact);
}

void CTimerMgr::DelTimer( CTimer* timer )
{
    m_timer_mgr->DelTimer(timer->get_timer());
    timer->set_timer(NULL);
}

bool CTimerMgr::Run( void )
{
    return m_timer_mgr->Update();
}

void CTimerCloseServer::OnTimer( void )
{
    if (!CP2PSvrApp::Instance()->is_closing())
        return;

    CP2PSvrApp::Instance()->set_run(false);
}
